package com.example.onlinemarket.controller;

import com.example.onlinemarket.bean.*;
import com.example.onlinemarket.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("/shopping")
public class ShoppingController {
    private UserService userService;
    private GoodService goodService;
    private OrderService orderService;
    private OrderItemService orderItemService;
    @Autowired
    public void setGoodService(GoodService goodService){ this.goodService = goodService; }
    @Autowired
    public void setOrderItemService(OrderItemService orderItemService){ this.orderItemService = orderItemService; }
    @Autowired
    public void setOrderService(OrderService orderService){ this.orderService = orderService; }
    @Autowired
    public void setUserService(UserService userService){
        this.userService = userService;
    }

    private Logger logger;
    @Autowired
    public void setLogger() { this.logger = LoggerFactory.getLogger(ShoppingController.class);}

    //删除订单
    @RequestMapping("/delOrder")
    public String delOrder(HttpSession session, Integer orderId, String status){
        User loginUser = (User) session.getAttribute("loginUser");
        if(!loginUser.isRole()) {//必须为买家操作
            Order userOrder = orderService.getOrderByOrderId(orderId);
            if (userOrder.getUserId().equals(loginUser.getUserId())) {//必须为本人操作
                boolean flag = orderService.delOrderByOrderId(orderId)||
                                orderItemService.delOrderItemsByOrderId(orderId);
                if (flag) {
                    System.out.println("订单删除成功");
                } else {//若删除失败则事务回滚
                    // TODO: 2021/1/15 事务回滚
                    System.out.println("订单删除失败");
                }
                return "forward:/shopping/getUserOrder/" + status;
            }else {//若不是本人操作则返回
                // TODO: 2021/1/12 非法操作
                System.out.println("非法操作！不能操作他人订单！");
                return "forward:/shopping/shoppingIndex";
            }
        }else{//若是商家操作则返回卖家首页
            // TODO: 2021/1/12 非法操作
            System.out.println("非法操作！商家不能操作他人订单！");
            return "forward:/shop/shopIndex";
        }
    }

    @RequestMapping("/userInfo")
    public String userInfo(){
        return "shopping/userInfo";
    }

    @RequestMapping("/delOrderItem")
    public String delOrderItem(HttpSession session, Integer orderId, Integer goodId){
        User loginUser = (User) session.getAttribute("loginUser");
        if (!loginUser.isRole()){
            Order userOrder = orderService.getOrderByOrderId(orderId);
            if(userOrder.getUserId().equals(loginUser.getUserId())){
                boolean flag = orderItemService.delOrderItem(orderId, goodId);
                logger.debug(flag?"购物车鲜花删除成功":"购物车鲜花删除失败");
                return "forward:/shopping/shoppingCart/"+loginUser.getUserName()+"/false";
            }else{
                // TODO: 2021/1/12 非法操作
                System.out.println("非法操作！不能操作他人订单！");
                return "forward:/shopping/shoppingIndex";
            }
        }else{
            System.out.println("非法操作！商家不能操作购物车！");
            return "forward:/shop/shopIndex";
        }
    }

    @RequestMapping("/shoppingIndex")
    public String index(Model model){
        model.addAttribute("searchItem",new SearchItem("搜索商家","鲜花类型"));
        return "pages/shopping/shoppingIndex";
    }

    //添加鲜花到购物车
    @RequestMapping("/addGood/{goodId}")
    public String addGood(HttpSession session, @PathVariable("goodId")Integer goodId, @RequestParam("visitMethod") String visitMethod) {
        User loginUser = (User) session.getAttribute("loginUser");
        System.out.println("卖家信息"+loginUser.toString());
        if (!loginUser.isRole()) {//必须是买家操作
            Order userOrder = orderService.getUserShoppingOrder(loginUser.getUserId());
//
//            if (userOrder==null){
//                userOrder = orderService.getUserShoppingOrder(loginUser.getUserId());
//                System.out.println("卖家信息==订单信息==更新后"+userOrder.toString());
//            }


            Integer shopId = goodService.getShopIdByGoodId(goodId);
            String shopName = userService.getUserNameByUserId(shopId);
            String viewName = null;
            if (visitMethod.equals("userSearch")) {//取得合适的返回路径
                viewName = "forward:/shop/goShopping/" + shopName;
            } else {
                viewName = "forward:/get/goodInfo/" + goodId;
            }
            if (userOrder != null) {//若存在购物车则将鲜花加入购物车
                System.out.println("判断购物车不为空");
                Integer goodNum = 1;
                String msg = orderItemService.addOrderItem(userOrder.getOrderId(), goodId, goodNum);
                System.out.println("打印添加购物车结果"+msg);
                if (msg != null) {
                    System.out.println(msg);
                }
            }else{
                orderService.addShoppingCart(loginUser.getUserId(), goodId);
                userOrder = orderService.getUserShoppingOrder(loginUser.getUserId());

                System.out.println("打印添加购物车结果null=="+userOrder.toString());
                Integer goodNum = 1;
                String msg = orderItemService.addOrderItem(userOrder.getOrderId(), goodId, goodNum);
                System.out.println("打印添加购物车结果"+msg);
                if (msg != null) {
                    System.out.println("添加商品成功"+msg);
                }
            }
            return viewName;
        } else {//若为卖家操作则返回店铺首页
            System.out.println("卖家信息==判定为商家");
            // TODO: 2021/1/10 非法权限操作
            return "forward:/shop/shopIndex";
        }
    }

    @RequestMapping("/noShoppingCart")
    public String noShoppingCart(){ return "pages/shopping/noShoppingCart"; }

    //清空购物车操作
    @RequestMapping("/cleanShoppingCart/{orderId}")
    public String cleanShoppingCart(Model model, HttpSession session, @PathVariable("orderId") Integer orderId){
        User loginUser = (User) session.getAttribute("loginUser");
        if(!loginUser.isRole()) {//用户身份必须为买家，否则视为非法操作
            Order shoppingCart = orderService.getOrdersByUserId(loginUser.getUserId(), "购物车").get(0);
            if (shoppingCart == null) {//订单号如不存在则错误
                logger.debug("订单号错误！不存在订单号为" + orderId + "的购物车！");
                return "forward:/shopping/shoppingCart";
            }else{//若订单号存在则确定是否为本人操作
                if(shoppingCart.getUserId().equals(loginUser.getUserId())){
                    //清空购物车
                    boolean flag = orderItemService.cleanShoppingCart(shoppingCart.getOrderId());
                    System.out.println(flag?"清空购物车成功":"清空购物车失败");
                    if(flag){//若清空购物车成功则显示购物车为空
                        model.addAttribute("searchItem",new SearchItem("搜索商家","鲜花类型"));
                        return "pages/shopping/noShoppingCart";
                    }else{//若清空购物车失败则返回购物车页面
                        System.out.println("购物车清空失败，请重试");
                        return "forward:/shopping/shoppingCart/"+loginUser.getUserName()+"/true";
                    }
                }else{//若不是本人则返回首页
                    System.out.println("非法操作6，不能访问其他人的购物车！");
                    return "forward:/shopping/shoppingCart";
                }
            }
        }else{//若不是买家则返回卖家界面
            System.out.println("非法操作9，商家不能操作购物车！");
            return "forward:/shop/shopIndex";
        }
    }

    //下单
    @RequestMapping("/settlement")
    public String settlement(Model model, HttpSession session, String address, Integer userId, Integer orderId){
        User loginUser = (User) session.getAttribute("loginUser");
        if(!loginUser.isRole()){//用户必须是买家
            if(loginUser.getUserId().equals(userId)){//必须是本人操作
                if (address!=null&&!address.equals("")) {//用户地址必须不为空
                    //若表单地址不为空则更新用户地址信息
                    if(loginUser.getAddress()!=null&&!loginUser.getAddress().equals(address))
                        userService.updateUserAddress(loginUser.getUserId(), address);
                    //用户进行支付
                    boolean isPaid = orderService.payment(userId, orderId);
                    if (isPaid) {//若支付成功则进行订单状态更新
                        boolean flag1 = orderService.updateOrderStatus(orderId, "待发货", loginUser.getAddress());
                        boolean flag2 = goodService.updateSellNumAndQuantity(orderId, true);
                        if (flag1||flag2) {//订单状态更新成功，提示支付成功
                            System.out.println("支付成功，等待商家发货");
                            return "forward:/shopping/shoppingIndex";
                        } else {//订单状态更新失败，提示系统错误
                            System.out.println("系统错误！无法完成订单状态转换！");
                            // TODO: 2021/1/11  事务回滚
                            return "forward:/shopping/shoppingIndex";
                        }
                    } else {//支付失败，提示系统错误
                        System.out.println("系统错误！无法完成订单状态转换！");
                        // TODO: 2021/1/11  事务回滚
                        return "forward:/shopping/shoppingIndex";
                    }
                }else{//若地址为空则跳转回购物车
                    String addressMsg = "地址不能为空！";
                    model.addAttribute("addressMsg", addressMsg);
                    return "forward:/shopping/shoppingCart/"+loginUser.getUserName()+"/false";
                }
            }else{//若不是本人操作则返回买家首页
                System.out.println("非法操作6，不能访问其他人的购物车！");
                return "forward:/shopping/shoppingIndex";
            }
        }else{//若不是买家则返回卖家首页
            System.out.println("非法操作9，商家不能操作购物车！");
            return "forward:/shop/shopIndex";
        }
    }

    @RequestMapping("/shoppingCart/{userName}/{back}")
    public String shoppingCart(HttpSession session, @PathVariable("back") boolean back, Model model,@PathVariable("userName") String userName){
        User loginUser = (User) session.getAttribute("loginUser");
        model.addAttribute("searchItem",new SearchItem("搜索商家","鲜花类型"));
        if(loginUser.getUserName().equals(userName)){
            if(orderService.haveShoppingCart(loginUser.getUserId())){
                Order shoppingCart = orderService.getUserShoppingOrder(loginUser.getUserId());
                List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderId(shoppingCart.getOrderId());
                if(orderItems.isEmpty())
                    return "pages/shopping/noShoppingCart";
                else {
                    List<OrderItemInfo> orderItemInfos = new ArrayList<>();
                    shoppingCart.setCount(0.0);
                    for (OrderItem orderItem:orderItems) {
                        Good good = goodService.getGoodById(orderItem.getGoodId());
                        orderItemInfos.add(new OrderItemInfo(good, orderItem.getGoodNUm(), orderItem.getNote(), userService.getUserNameByUserId(good.getUserId())));
                        shoppingCart.setCount(shoppingCart.getCount() + orderItem.getGoodNUm() * good.getSellPrice());
                    }
                    model.addAttribute("orderItemInfos", orderItemInfos);
                    model.addAttribute("shoppingCart", shoppingCart);
                    return "pages/shopping/shoppingCart";
                }
            }else return "pages/shopping/noShoppingCart";
        }else{
            System.out.println("非法操作6，不能访问其他人的购物车！");
            return loginUser.isRole()?"forward:/shop/shopIndex":"forward:/shopping/shopIndex";
        }
    }

    //更新订单状态
    @RequestMapping("/updateStatus")
    public String updateStatus(HttpSession session, boolean split, String status, Integer orderId, String goodStatus){
        User loginUser = (User) session.getAttribute("loginUser");
        if(!loginUser.isRole()) {//必须是买家操作
            Order userOrder = orderService.getOrderByOrderId(orderId);
            //必须是本人操作
            if (userOrder.getUserId().equals(loginUser.getUserId())) {
                if (split){//判断传递的字符串是否需要分割
                    goodStatus = goodStatus.split("-")[0];
                }
                //更新订单和订单详情状态
                boolean flag1 = orderService.updateOrderStatus(orderId, goodStatus, loginUser.getAddress());
                boolean flag2 = orderItemService.updateOrderItemStatus(orderId, goodStatus);
                if (flag1 || flag2) {
                    System.out.println("提交"+goodStatus+"申请");
                } else {
                    // TODO: 2021/1/12 事务回滚
                    System.out.println("申请"+goodStatus+"失败");
                }
                return "forward:/shopping/getUserOrder/" + status;
            }else {//若不是本人操作则返回买家首页
                // TODO: 2021/1/12 非法操作
                System.out.println("非法操作！不能操作他人订单！");
                return "forward:/shopping/shoppingIndex";
            }
        }else{//若为卖家则返回卖家界面
            // TODO: 2021/1/12 非法操作
            System.out.println("非法操作！商家不能操作他人订单！");
            return "forward:/shop/shopIndex";
        }
    }

    @RequestMapping("/getUserOrder/{status}")
    public String getUserOrder(Model model, HttpSession session, @PathVariable("status") String status){
        User loginUser = (User) session.getAttribute("loginUser");
        if(!loginUser.isRole()) {
            model = orderService.getOrders(model, loginUser.getUserId(), status);
            return "pages/shopping/userOrder/" + status;
        }else{
            System.out.println("非法操作！商家不能查看用户订单！");
            return "forward:/shop/shopIndex";
        }
    }
}
